package cn.gzjp.modules.logis.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Map;

import cn.gzjp.common.utils.BaiduAPI;
import cn.hutool.core.util.StrUtil;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import cn.gzjp.common.utils.DateUtils;
import cn.gzjp.common.utils.MyBeanUtils;
import cn.gzjp.common.persistence.Page;
import cn.gzjp.common.web.BaseController;
import cn.gzjp.common.utils.StringUtils;
import cn.gzjp.common.utils.excel.ExportExcel;
import cn.gzjp.common.utils.excel.ImportExcel;
import cn.gzjp.modules.logis.entity.LogisFreightPrice;
import cn.gzjp.modules.logis.service.LogisFreightPriceService;

/**
 * 城市运费单价Controller
 * @author zengcp
 * @version 2018-05-24
 */
@Controller
@RequestMapping(value = "${adminPath}/logis/logisFreightPrice")
public class LogisFreightPriceController extends BaseController {

	@Autowired
	private LogisFreightPriceService logisFreightPriceService;
	
	
	/**
	 * 城市运费单价列表页面
	 */
	@RequiresPermissions("logis:logisFreightPrice:list")
	@RequestMapping(value = {"list", ""})
	public String list(LogisFreightPrice logisFreightPrice, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<LogisFreightPrice> page = logisFreightPriceService.findPage(new Page<LogisFreightPrice>(request, response), logisFreightPrice); 
		model.addAttribute("page", page);
		return "modules/logis/logisFreightPriceList";
	}

	/**
	 * 查看，增加，编辑城市运费单价表单页面
	 */
	@RequiresPermissions(value={"logis:logisFreightPrice:view","logis:logisFreightPrice:add","logis:logisFreightPrice:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(LogisFreightPrice logisFreightPrice, Model model) {
		model.addAttribute("logisFreightPrice", logisFreightPrice);
		return "modules/logis/logisFreightPriceForm";
	}

	/**
	 * 保存城市运费单价
	 */
	@RequiresPermissions(value={"logis:logisFreightPrice:add","logis:logisFreightPrice:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(LogisFreightPrice logisFreightPrice, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, logisFreightPrice)){
			return form(logisFreightPrice, model);
		}
		if(!logisFreightPrice.getIsNewRecord()){//编辑表单保存
			LogisFreightPrice t = logisFreightPriceService.get(logisFreightPrice.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(logisFreightPrice, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			Map<String, Double> startMap = BaiduAPI.getLngAndLat(t.getStartCity());
			String endAddress = t.getEndCity();
			if(StrUtil.isNotBlank(t.getEndArea())){
				endAddress = endAddress+t.getEndArea();
			}
			Map<String, Double> endMap = BaiduAPI.getLngAndLat(endAddress);
			String distanceStr = BaiduAPI.getDistance(startMap, endMap);
			if ("0".equals(distanceStr)) {
				distanceStr = BaiduAPI.getDistance(startMap, endMap);
			}
			int distance = Integer.parseInt(distanceStr);
			t.setDistance(distance/1000);
			int price = (distance / 10000) * 2;
			if (price < 100) {
				price = price + 20;
			}
			t.setReferPrice(price+"");
			logisFreightPriceService.save(t);//保存
		}else{//新增表单保存
			Map<String, Double> startMap = BaiduAPI.getLngAndLat(logisFreightPrice.getStartCity());
			String endAddress = logisFreightPrice.getEndCity();
			if(StrUtil.isNotBlank(logisFreightPrice.getEndArea())){
				endAddress = endAddress+logisFreightPrice.getEndArea();
			}
			Map<String, Double> endMap = BaiduAPI.getLngAndLat(endAddress);
			String distanceStr = BaiduAPI.getDistance(startMap, endMap);
			if ("0".equals(distanceStr)) {
				distanceStr = BaiduAPI.getDistance(startMap, endMap);
			}
			int distance = Integer.parseInt(distanceStr);
			logisFreightPrice.setDistance(distance/1000);
			int price = (distance / 10000) * 2;
			if (price < 100) {
				price = price + 20;
			}
			logisFreightPrice.setReferPrice(price+"");
			logisFreightPriceService.save(logisFreightPrice);//保存
		}
		addMessage(redirectAttributes, "保存城市运费单价成功");
		return redirect("/logis/logisFreightPrice/");
	}
	
	/**
	 * 删除城市运费单价
	 */
	@RequiresPermissions("logis:logisFreightPrice:del")
	@RequestMapping(value = "delete")
	public String delete(LogisFreightPrice logisFreightPrice, RedirectAttributes redirectAttributes) {
		logisFreightPriceService.delete(logisFreightPrice);
		addMessage(redirectAttributes, "删除城市运费单价成功");
		return redirect("/logis/logisFreightPrice/");
	}


	/**
	 * 司机报价测试
	 */
	@RequestMapping(value = "driverPrice")
	public String driverPrice(LogisFreightPrice logisFreightPrice, RedirectAttributes redirectAttributes) {
		if(StrUtil.isBlank(logisFreightPrice.getUnitPriceBase())){
			addMessage(redirectAttributes, "测试失败，清先输入单价基数");
			return redirect("/logis/logisFreightPrice/");
		}
		if(logisFreightPrice.getDriverPrice()==0){
			addMessage(redirectAttributes, "测试失败，清先输入报价");
			return redirect("/logis/logisFreightPrice/");
		}

		int score = 75;

		int dif = logisFreightPrice.getDriverPrice() - Integer.parseInt(logisFreightPrice.getUnitPriceBase());//差价 低于市场指导价
		if (dif <= 0 && dif >= -10) {
			score = score + (-dif);//
		}
		if (dif < -10 && dif >= -20) {
			score = 10 + score + (-dif / 2);//
		}
		if (dif < -20 && dif >= -100) {
			score = 20 + score - ((dif + 20) / 10);//
		}
		if (dif < -100) {
			score = 98;//
		}
		if (dif > 0 && dif <= 50) {
			score = score - dif;
		}
		if (dif > 50 && dif <= 150) {
			score = 25 - ((dif - 50) / 5);
		}
		if (dif > 150) {//高于市场价150
			score = 9;
		}
		if (score > 100) {
			score = 98;
		}
		if (score < 9) {
			score = 9;
		}
		logisFreightPrice.setScore(score);
		logisFreightPriceService.save(logisFreightPrice);
		addMessage(redirectAttributes, "测试成功!");
		return redirect("/logis/logisFreightPrice/");
	}

	/**
	 * 司机返程报价测试
	 */
	@RequestMapping(value = "driverPrice2")
	public String driverPrice2(LogisFreightPrice logisFreightPrice, RedirectAttributes redirectAttributes) {
		if(StrUtil.isBlank(logisFreightPrice.getReturnUnitPriceBase())){
			addMessage(redirectAttributes, "测试失败，清先输入返程单价基数");
			return redirect("/logis/logisFreightPrice/");
		}
		if(logisFreightPrice.getDriverPrice2()==0){
			addMessage(redirectAttributes, "测试失败，清先输入报价");
			return redirect("/logis/logisFreightPrice/");
		}

		int score = 75;

		int dif = logisFreightPrice.getDriverPrice2() - Integer.parseInt(logisFreightPrice.getReturnUnitPriceBase());//差价 低于市场指导价
		if (dif <= 0 && dif >= -10) {
			score = score + (-dif);//
		}
		if (dif < -10 && dif >= -20) {
			score = 10 + score + (-dif / 2);//
		}
		if (dif < -20 && dif >= -100) {
			score = 20 + score - ((dif + 20) / 10);//
		}
		if (dif < -100) {
			score = 98;//
		}
		if (dif > 0 && dif <= 50) {
			score = score - dif;
		}
		if (dif > 50 && dif <= 150) {
			score = 25 - ((dif - 50) / 5);
		}
		if (dif > 150) {//高于市场价150
			score = 9;
		}
		if (score > 100) {
			score = 98;
		}
		if (score < 9) {
			score = 9;
		}
		logisFreightPrice.setScore2(score);
		logisFreightPriceService.save(logisFreightPrice);
		addMessage(redirectAttributes, "测试成功!");
		return redirect("/logis/logisFreightPrice/");
	}


	
	/**
	 * 批量删除城市运费单价
	 */
	@RequiresPermissions("logis:logisFreightPrice:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			logisFreightPriceService.delete(logisFreightPriceService.get(id));
		}
		addMessage(redirectAttributes, "删除城市运费单价成功");
		return redirect("/logis/logisFreightPrice/?repage");
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("logis:logisFreightPrice:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(LogisFreightPrice logisFreightPrice, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "城市运费单价"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<LogisFreightPrice> page = logisFreightPriceService.findPage(new Page<LogisFreightPrice>(request, response, -1), logisFreightPrice);
    		new ExportExcel("城市运费单价", LogisFreightPrice.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出城市运费单价记录失败！失败信息："+e.getMessage());
		}
		return redirect("/logis/logisFreightPrice/");
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("logis:logisFreightPrice:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<LogisFreightPrice> list = ei.getDataList(LogisFreightPrice.class);
			for (LogisFreightPrice logisFreightPrice : list){
				try{
					logisFreightPriceService.save(logisFreightPrice);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条城市运费单价记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条城市运费单价记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入城市运费单价失败！失败信息："+e.getMessage());
		}
		return redirect("/logis/logisFreightPrice/?repage");
    }
	
	/**
	 * 下载导入城市运费单价数据模板
	 */
	@RequiresPermissions("logis:logisFreightPrice:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "城市运费单价数据导入模板.xlsx";
    		List<LogisFreightPrice> list = Lists.newArrayList(); 
    		new ExportExcel("城市运费单价数据", LogisFreightPrice.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return redirect("/logis/logisFreightPrice/?repage");
    }
	@ModelAttribute
	public LogisFreightPrice get(@RequestParam(required=false) String id) {
		LogisFreightPrice entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = logisFreightPriceService.get(id);
		}
		if (entity == null){
			entity = new LogisFreightPrice();
		}
		return entity;
	}
	

}